import React, { useCallback, useEffect, useRef, useState } from 'react';
import {
  Layout,
  Button,
  Typography,
  Spin,
  Card,
  Space,
  Tag,
  Tooltip,
  Empty,
} from 'antd';
import {
  LeftOutlined,
  RightOutlined,
  ExperimentOutlined,
} from '@ant-design/icons';
import MainLayout from 'components/MainLayout';
import TechGraph from 'components/TechGraph';
import WordCloud from 'components/WordCloud';
import { techInsightApi } from 'services';
import { GraphNeo4jParams, Relationship, Node, TopK } from 'types/tech-insight';
import { fetchEventSource } from '@microsoft/fetch-event-source';
import { DIFY_API_URL, TECH_INSIGHT_API_TOKEN } from 'constant';

import styles from './index.module.css';

const { Content, Sider } = Layout;
const { Title, Paragraph, Text } = Typography;

const industries = [
  { key: '新材料', icon: '🔬', count: '28,638' },
  { key: '人参', icon: '🌿', count: '7,547' },
  { key: '大农业', icon: '🌾', count: null },
  { key: '大装备', icon: '⚙️', count: null },
  { key: '大数据', icon: '💻', count: null },
  { key: '新能源', icon: '⚡', count: null },
  { key: '新医药', icon: '💊', count: null },
  { key: '光电信息', icon: '📡', count: null },
  { key: '量子技术', icon: '⚛️', count: null },
  { key: '人工智能', icon: '🤖', count: null },
];

const TechInsight: React.FC = () => {
  const [collapsed, setCollapsed] = useState(false);
  const [selectedIndustry, setSelectedIndustry] = useState('新材料');
  const [loading, setLoading] = useState(false);
  const [nodes, setNodes] = useState<Node[]>([]); // 节点数据
  // 节点关联关系
  const [nodeRelationships, setNodeRelationships] = useState<Relationship[]>(
    []
  );
  const [topKGraphs, setTopKGraphs] = useState<TopK[]>([]); // 关键词数据
  const [agentThoughtLoading, setAgentThoughtLoading] = useState(false); // 产业新兴技术预测结果
  const [agentThought, setAgentThought] = useState<string>(''); // 产业新兴技术预测结果

  // 添加初始化标记和上一次的产业值追踪
  const prevIndustry = useRef<string | null>(null);

  const username = localStorage.getItem('username') || '';

  // 选择产业
  const handleIndustrySelect = (industry: string) => {
    setLoading(true);
    setSelectedIndustry(industry);
  };

  // 调用Dify接口，获取产业新兴技术预测结果
  const fetchAgentThought = useCallback(async () => {
    setAgentThoughtLoading(true);

    try {
      fetchEventSource(DIFY_API_URL + '/chat-messages', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: TECH_INSIGHT_API_TOKEN,
        },
        body: JSON.stringify({
          query: selectedIndustry,
          inputs: {},
          response_mode: 'streaming',
          user: username,
          conversation_id: '',
        }),
        onmessage(msg) {
          if (!msg.data) return;

          const data = JSON.parse(msg.data);
          let agentThoughtData = '';

          switch (data.event) {
            case 'agent_thought':
              agentThoughtData += data.thought;
              setAgentThought(agentThoughtData);
              break;
            case 'message_end':
            case 'error':
              setAgentThoughtLoading(false);
              break;
          }
        },
      });
    } catch (error) {
      console.error('获取产业新兴技术预测结果失败:', error);
      setAgentThoughtLoading(false);
    }
  }, [selectedIndustry, username]);

  // 获取技术洞察数据
  const fetchTechInsight = useCallback(async () => {
    setLoading(true);
    try {
      const params: GraphNeo4jParams = {
        industryName: selectedIndustry,
        // topK: 30,
        // limit: 30,
      };

      const res = await techInsightApi.getGraphNeo4j(params);

      if (res.code === 200) {
        setNodes(res.data.nodes || []);
        setNodeRelationships(res.data.relationships || []);
        setTopKGraphs(res.data.topK || []);
      }
    } catch (error) {
      console.error('获取报告列表失败:', error);
    } finally {
      setLoading(false);
    }
  }, [selectedIndustry]);

  // 监听筛选条件变化 // 使用 ref 控制调用
  useEffect(() => {
    if (selectedIndustry && selectedIndustry !== prevIndustry.current) {
      prevIndustry.current = selectedIndustry;
      fetchTechInsight();
      fetchAgentThought();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedIndustry]);

  const categories = Array.from(new Set(nodes.map((node) => node.category)));

  const currentIndustry = industries.find(
    (industry) => industry.key === selectedIndustry
  );

  return (
    <MainLayout>
      <Layout className={styles.layout}>
        <Sider
          width={250}
          collapsed={collapsed}
          className={styles.sider}
          trigger={null}
        >
          <div className={styles.siderHeader}>
            <ExperimentOutlined className={styles.siderIcon} />
            {!collapsed && <span className={styles.siderTitle}>产业选择</span>}
            <Button
              type="text"
              className={styles.collapseButton}
              onClick={() => setCollapsed(!collapsed)}
              icon={collapsed ? <RightOutlined /> : <LeftOutlined />}
            />
          </div>
          <div className={styles.industryList}>
            {industries.map(({ key, icon }) => (
              <Tooltip title={collapsed ? key : ''} placement="right">
                <Button
                  key={key}
                  type={selectedIndustry === key ? 'primary' : 'default'}
                  onClick={() => handleIndustrySelect(key)}
                  className={styles.industryButton}
                >
                  <span className={styles.industryIcon}>{icon}</span>
                  {!collapsed && key}
                </Button>
              </Tooltip>
            ))}
          </div>
        </Sider>

        <Content className={styles.content}>
          {loading ? (
            <div className={styles.loading}>
              <Spin size="large" />
            </div>
          ) : (
            <div className={styles.contentWrapper}>
              <Card className={styles.section}>
                <Title level={3} style={{ marginTop: 0 }}>
                  <Space>
                    数据说明
                    <Tag color="blue">专利数据</Tag>
                  </Space>
                </Title>
                <div className={styles.dataInfo}>
                  <Text strong>检索式：</Text>
                  <Text code>TIAB=("汽车" OR "新能源" OR "新能源汽车")</Text>
                  <br />
                  <Text strong>时间段：</Text>
                  <Text>2019年1月 - 2023年12月</Text>
                  <br />
                  <Text strong>数据量：</Text>
                  {currentIndustry?.count ? (
                    <Text type="success">{currentIndustry?.count}条</Text>
                  ) : (
                    <Text type="danger">~</Text>
                  )}
                </div>
              </Card>

              <Card className={styles.section}>
                <Title level={3} style={{ marginTop: 0 }}>
                  <Space>
                    产业新兴技术图谱
                    <Tag color="green">关联分析</Tag>
                  </Space>
                </Title>

                {!nodes?.length || !nodeRelationships?.length ? (
                  <Empty
                    description="暂无数据"
                    style={{
                      height: '400px', // 设置一个合适的高度
                      display: 'flex',
                      flexDirection: 'column',
                      justifyContent: 'center',
                    }}
                  />
                ) : (
                  <TechGraph
                    nodes={nodes}
                    relationships={nodeRelationships}
                    categories={categories}
                  />
                )}
              </Card>

              <Card className={styles.section}>
                <Title level={3} style={{ marginTop: 0 }}>
                  <Space>
                    技术关键词预测
                    <Tag color="purple">词频分析</Tag>
                  </Space>
                </Title>

                {!topKGraphs?.length ? (
                  <Empty
                    description="暂无数据"
                    style={{
                      height: '400px', // 设置一个合适的高度
                      display: 'flex',
                      flexDirection: 'column',
                      justifyContent: 'center',
                    }}
                  />
                ) : (
                  <WordCloud
                    data={topKGraphs.map((item) => ({
                      name: item.name,
                      value: item.totalDegrees,
                      key: item.nodeId,
                    }))}
                  />
                )}
              </Card>

              <Card className={styles.section}>
                <Title level={3}>
                  <Space>
                    预测说明
                    <Tag color="orange">趋势分析</Tag>
                  </Space>
                </Title>
                {agentThoughtLoading ? (
                  <Spin
                    spinning={true}
                    style={{ width: '100%', margin: '20px auto' }}
                  />
                ) : (
                  <Paragraph className={styles.explanation}>
                    {agentThought || '暂无预测数据'}
                  </Paragraph>
                )}
              </Card>
            </div>
          )}
        </Content>
      </Layout>
    </MainLayout>
  );
};

export default TechInsight;
